<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use think\Db;
use think\Validate;

/**
 * 示例接口
 * 备注，第一次登录时，必须拿到openId
 */
class Faxin extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['taskList','tongzhi','upload','test'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['daka','addask','askList','tongzhi','applayJob','addQingjia','qingjiadetail','qingjiaList','userMoney','myApplayJob','renzheng','getProjectDaka','getDakaList','gongzidan'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    public function test()
    {
        die('999');
    }
    public function upload(){
        $attachment = null;
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }
        //$this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        $data  =array('code'=>1,'msg'=>'上传成功','data'=>['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        return json($data);
    }

    /**
     * 打卡
     * @ApiMethod (POST)
     * @param string $type
     * @param string $dizhi
     */
    public function daka()
    {
        $type = $this->request->post('type');
        $dizhi = $this->request->post('dizhi');
        $zaoStatus = $this->request->post('zaoStatus');
        $wanStatus = $this->request->post('wanStatus');
        $dakaprojectid = $this->request->post('dakaprojectid');
        if (!$type || !$dizhi) {
            $this->error(__('Invalid parameters'));
        }
        if($dizhi == 'undefined'){
            $this->error(__('无效地址'));
        }
        if($type ==1){
            $data = [
                'zao' => time(),
                'zaodizhi' => $dizhi,
                'zaoStatus' => $zaoStatus,
                'day'=>date("Y-m-d"),
                'addtime'=>time()
            ];
        }elseif ($type ==2){
            $data = [
                'wan' =>time(),
                'wandizhi' => $dizhi,
                'wanStatus' => $wanStatus
            ];
        }
        $data['uid'] = $this->auth->id;
        $data['dakaprojectid'] = $dakaprojectid;
        //db('department_admin')->where('department_id', 'in', $childIds)->delete();
        $where = ['uid' =>  $this->auth->id, 'day' => date("Y-m-d")];
        $res = Db::name('yonghuday')->where($where)->find();
        if(empty($res)){
            Db::name('yonghuday')->insert($data);
            //是否迟到
            $pWhere = ['id'=>$dakaprojectid];
            $reGongzuoShijian = Db::name('gongzuo_project')->field('gongzuoshijianM')->where($pWhere)->find();
            $secondNow =  date('H:i:s',time());
            $pieces = explode(":", $secondNow);
            $total  = $pieces[0]*60*60 + $pieces[1]*60 +$pieces[2];

            if($type ==1   ){
                //记录迟到
                $Gwhere['uid'] = $this->auth->id;
                $Gwhere['pid'] = $dakaprojectid;
                $Gwhere['zhangqi'] = date('Y-m',time());
                $gRes  =  Db::name('yonghuday_chidao')->where($Gwhere)->find();
                if(empty($gRes)){
                    $Gdata = $Gwhere;
                    $Gdata['chidaoCishu'] = 1;
                    $Gdata['chidaobeizhu'] = date('yY-m-d H:i:s',time());
                    $Gdata['addtime'] = time();
                    Db::name('yonghuday_chidao')->insert($Gdata);
                }else{
                    //$Gdata = $Gwhere;
                    if($total > $reGongzuoShijian['gongzuoshijianM']){
                        $Gdata['chidaoCishu'] = $gRes['chidaoCishu']+1;
                        $Gdata['chidaobeizhu'] = $gRes['chidaobeizhu'] . ',' .date('Y-m-d H:i:s',time());
                    }
                    $Gdata['dakaCishu'] = $gRes['dakaCishu']+1;
                    Db::name('yonghuday_chidao')->where($Gwhere)->update($Gdata);
                }
            }
        }else{
            Db::name('yonghuday')->where($where)->update($data);
        }
        $this->success('打卡成功', ['action' => 'daka']);
    }
    /**
     * 某个项目的打卡信息列表
     * @ApiMethod (GET)
     */
    public function getDakaList()
    {
        $tId =    $this->request->get('tId');
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $where = array();
        if(!empty($tId)){
            $where = ['dakaprojectid'=>$tId];
        }
        //打卡信息
        $where['uid'] = $this->auth->id;
        $total = Db::name('yonghuday')->where($where)->count();
        $list  = Db::name('yonghuday')->where($where)->limit(($page-1)*$pageSize, $pageSize)->select();

        if(!empty($list)){
            foreach ( $list as $Item =>$value) {
                $list[$Item]['zao'] = empty($value['zao']) ? '' : $value['zao'];
                $list[$Item]['zaoStatus'] = empty($value['zaoStatus']) ? '' : $value['zaoStatus'];
                $list[$Item]['wan'] = empty($value['wan']) ? '' : $value['wan'];
                $list[$Item]['wanStatus'] = empty($value['wanStatus']) ? '' : $value['wanStatus'];
            }
        }
        $pagesNum  = ceil($total/$pageSize);
        $data  =array('code'=>1,'msg'=>'打卡列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }
    /**
     * 认证
     * @ApiMethod (POST)
     * @param string $type
     * @param string $dizhi
     */
    public function renzheng()
    {
        $realname = $this->request->post('realname');
        $shenfenzheng = $this->request->post('shenfenzheng');


        if (!$realname || !$shenfenzheng) {
            $this->error(__('Invalid parameters'));
        }

        $data = [
            'realname' =>$realname,
            'shenfenzheng' => $shenfenzheng
        ];
        //db('department_admin')->where('department_id', 'in', $childIds)->delete();
        $where = ['id' =>  $this->auth->id];

        Db::name('user')->where($where)
            ->update($data);
        $this->success('认证成功');
    }
    /**
    * 职位列表
    * @ApiMethod (GET)
    */
    public function taskList()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $total = Db::name('gongzuo_project')->count();
        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('gongzuo_project')->limit(($page-1)*$pageSize, $pageSize)->select();
        //$thisUserObj = new User();
        if(!empty($list)){
            foreach ($list as $Item =>$value){
                $cUser  = Db::name('user')->where(['id'=>$value['cUid']])->find();
                $url  = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                $url .= "://" . $_SERVER['HTTP_HOST'];
                //$url .= $_SERVER['REQUEST_URI'];
                $thisAvatar = $url.$cUser['avatar'];
                $list[$Item]['fubuzheTouxiang'] = $thisAvatar;
                $list[$Item]['fubuzheMobile'] = $cUser['mobile'];
            }
        }
        //echo  Db::name('gongzuo_project')->getLastSql();
        $data  =array('code'=>1,'msg'=>'工作列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }
    /**
     * 通知列表
     * @ApiMethod (GET)
     */
    public function tongzhi()
    {
        $type =    $this->request->get('type');
        //$title = $this->request->get('title');
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $where = array();
        if(!empty($type)){
            $where = ['type'=>$type];
        }
        $total = Db::name('gongzuotongzhi')->where($where)->count();
        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('gongzuotongzhi')->where($where)->order(['id'=>'desc'])->limit(($page-1)*$pageSize, $pageSize)->select();

        $data  =array('code'=>1,'msg'=>'通知列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }
    /**
     * 某个项目的打卡信息
     * @ApiMethod (GET)
     */
    public function getProjectDaka()
    {
        $tId =    $this->request->get('tId');
        $where = array();
        if(!empty($tId)){
            $where = ['id'=>$tId];
        }
        $list  = Db::name('gongzuo_project')->field(['gongzuoshijianM','gongzuoshijianA','dakadizhi','longitude','latitude'])->where($where)->find();
        $list['curentTime'] = time();
        //打卡信息
        $whereU = ['uid'=>$this->auth->id,'day'=>date("Y-m-d")];
        $listU  = Db::name('yonghuday')->field(['zao','wan','zaoStatus','wanStatus'])->where($whereU)->find();
        if($list['gongzuoshijianM']<10){
            $list['gongzuoshijianM']= '0'.$list['gongzuoshijianM'];
        }
        $list['zao'] = empty($listU['zao'])?'':$listU['zao'];
        $list['zaoStatus'] = empty($listU['zaoStatus'])?'':$listU['zaoStatus'];
        $list['wan'] = empty($listU['wan'])?'':$listU['wan'];
        $list['wanStatus'] = empty($listU['wanStatus'])?'':$listU['wanStatus'];

        //echo  Db::name('gongzuo_project')->getLastSql();
        $data  =array('code'=>1,'msg'=>'打卡时间，地址','data'=>$list);
        return json($data);
    }
    /**
     * 反饋列表
     * @ApiMethod (GET)
     */
    public function askList()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $type = $this->request->get('type');
        $whereU = ['uid'=>$this->auth->id];
        if(!empty($type)){
            $whereU['type'] = $type;
        }
        $total = Db::name('gongzuofankui')->where($whereU)->count();
        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('gongzuofankui')->where($whereU)->limit(($page-1)*$pageSize, $pageSize)->order('id desc')->select();
        //$thisUserObj = new User();
        $blist = array();
        if(!empty($list)){
            foreach ($list as $Item =>&$value){
                if(!empty($value['files'])){
                    //$url  = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                    //$url .= "://" . $_SERVER['HTTP_HOST'].$value['files'];
                    $list[$Item]['fullpath'] = $value['files'];
                    //echo $value['create_time'];
                    $list[$Item]['answerTime'] = date('Y-m-d H:i:s',$value['answerTime']);
                    $list[$Item]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
                }
                $blist[]  =  $list[$Item];
            }
        }
        //echo  Db::name('gongzuo_project')->getLastSql();
        $data  =array('code'=>1,'msg'=>'工作列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $blist]);
        return json($data);
    }

    /**
     * 问题反馈
     * @ApiMethod (POST)
     * @param string $type
     * @param string $title
     * @param string $content
     *
     */
    public function addask()
    {
        $type = $this->request->post('type');//反馈类型1，工作反馈，2，系统反馈，
        $tag = $this->request->post('tag');

        $title = $this->request->post('title');
        $tid = $this->request->post('tid');  //工作id
        $content = $this->request->post('content');
        $files = $this->request->post('files');

        if (!$type || !$title) {
            $this->error(__('Invalid parameters'));
        }
        $self  = $this->auth->getUserinfo();
        $data = [
            'uid' => $this->auth->id,
            'cid' => $self['cId'],
            'tid' => $tid,
            'tag' => $tag,
            'type' => $type,
            'title' => $title,
            'content'=>$content,
            'files'=>$files,
            'state'=>1,
            'createtime'=>time()
        ];
        Db::name('gongzuofankui')->insert($data);
        $this->success('反馈成功', ['action' => 'addAsk']);
    }
    /**
     * 工作申请
     * @ApiMethod (POST)
     * @param string $tid  工作id
     *
     */
    public function applayJob()
    {
        //如果申请过，就不能再申请
        $tid = $this->request->get('tid');  //二维码过来
        $beizhu = $this->request->post('beizhu');  //
        //统一通过code来申请
        //if(empty($tid)){
        $yaoqingcode = $this->request->post('yaoqingcode');  //工作
        if (empty($yaoqingcode) && empty($tid)) {
            $this->error(__('Invalid parameters'));
        }
        if(!empty($tid)){
            $where = ['id' =>  $tid];
        }
        if(!empty($yaoqingcode)){
            $where = ['yaoqingcode' =>  $yaoqingcode];
        }
        $res = Db::name('gongzuo_project')->where($where)->find();
        $tid =     $res['id'];
        $cUid =     $res['cUid'];
        //}

        //检查是否申请过
        $whereS = [
            'uid' => $this->auth->id,
            'tid' => $tid
        ];
        $re = Db::name('gongzuoshenqing')->where($whereS)->find();
        if(!empty($re)){
            $this->error('已经申请了项目');
        }
        $data = [
            'uid' => $this->auth->id,
            'tid' => $tid,
            'cid' => $cUid,
            'beizhu' => $beizhu,
            'addtime'=>time(),
            'status'=>1
        ];
        Db::name('gongzuoshenqing')->insert($data);
        Db::name('user')->where(['id'=>$this->auth->id])->update(['cId'=>$cUid]);
        $this->success('申请成功', ['action' => 'addAsk']);
    }
    /**
     * 我的工作申请
     * @ApiMethod (GET)
     * @param string $tid  工作id
     *
     */
    public function myApplayJob()
    {
        //SELECT * FROM fa_gongzuo_project WHERE id IN (SELECT tid FROM fa_gongzuoshenqing WHERE fa_gongzuoshenqing.uid =2)
        //$resArr = Db::query("SELECT * FROM fa_gongzuo_project WHERE id IN (SELECT tid FROM fa_gongzuoshenqing WHERE fa_gongzuoshenqing.uid =?)", [$this->auth->id]);
        $tids  = Db::name('gongzuoshenqing')->distinct(true)->where(['uid'=>$this->auth->id])->select();
        //$idString= '';

        $temArr =array();
        $myTidStartEndTime =array();
        if(!empty($tids)) {
            foreach($tids as $item=>$val){
                $temArr[] = $val['tid'];
                $myTidStartEndTime[$val['tid']]['addtime'] = $val['addtime'];
                $myTidStartEndTime[$val['tid']]['quittime'] = $val['quittime'];
            }
            //$idString = implode(',',$temArr);
        }
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $total = Db::name('gongzuo_project')->where('id','in',$temArr)->count();
        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('gongzuo_project')->where('id','in',$temArr)->limit(($page-1)*$pageSize, $pageSize)->select();
        $bList  = array();
        if(!empty($list)){
            foreach ($list as $Item =>$value){
                $cUser  = Db::name('user')->where(['id'=>$value['cUid']])->find();
                $url  = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                $url .= "://" . $_SERVER['HTTP_HOST'];
                //$url .= $_SERVER['REQUEST_URI'];
                $thisAvatar = $url.$cUser['avatar'];
                $list[$Item]['fubuzheTouxiang'] = $thisAvatar;
                $list[$Item]['fubuzheMobile'] = $cUser['mobile'];
                $list[$Item]['addtime']  = date('Y-m-d H:i:s',$myTidStartEndTime[$value['id']]['addtime']);
                $list[$Item]['quittime'] = date('Y-m-d H:i:s',$myTidStartEndTime[$value['id']]['quittime']);
                $bList[] = $list[$Item];
            }
        }
        //echo  Db::name('gongzuo_project')->getLastSql();
        $data  =array('code'=>1,'msg'=>'我申请的项目列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }
    /**
     * 添加请假
     * @ApiMethod (POST)
     * @param string $type
     * @param string $reason
     * @param string $startime
     * @param string $endtime
     * @param string $file
     */
    public function addQingjia()
    {
        $projectid = $this->request->post('projectid');
        $type = $this->request->post('type');//请假类型(固定)，1，请假,2，外出，3，休假，4，其他
        $reason = $this->request->post('reason');
        $startime = $this->request->post('startime');
        $endtime = $this->request->post('endtime');
        $files = $this->request->post('files');
        if (!$type || !$reason) {
            $this->error(__('Invalid parameters'));
        }
        $self  = $this->auth->getUserinfo();

        $data = [
            'uid' => $this->auth->id,
            'name' => $self['realname'],
            'projectid' => $projectid,
            'type' => $type,
            'reason' => $reason,
            'startime' => $startime,
            'endtime' => $endtime,
            'addtime'=>time(),
            'files'=>$files
        ];
        Db::name('yonghuqingjia')->insert($data);

        $this->success('请假成功', ['action' => 'addQingjia']);
    }

    /**
     * 请假列表
     * @ApiMethod (POST)
     */
    public function qingjiadetail()
    {
        $uid = $this->request->post('uid');
        $projectid = $this->request->post('projectid');
        $where = ['uid' =>  $this->auth->id, 'projectid' =>$projectid];
        $res = Db::name('yonghuqingjia')->where($where)->find();
        $this->success('返回列表', $res);
    }
    /**
     * 请假列表
     * @ApiMethod (POST)
     */
    public function qingjiaList()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $whereU =['uid'=>$this->auth->id];
        $total = Db::name('yonghuqingjia')->where($whereU)->count();
        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('yonghuqingjia')->where($whereU)->limit(($page-1)*$pageSize, $pageSize)->order('id desc')->select();
        $typeArr  = ['1'=>'事假','2'=>'病假','3'=>'年假','4'=>'调休假','5'=>'其它'];
        if(!empty($list)){
            foreach ($list as $Item =>&$value){
                $list[$Item]['typeS'] = $typeArr[$value['type']];
                $list[$Item]['startime'] = date('Y-m-d H:i:s',$value['startime']);
                $list[$Item]['endtime'] = date('Y-m-d H:i:s',$value['endtime']);
                $list[$Item]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
                if(!empty($value['files'])){
                    $list[$Item]['filesArr'] = explode(',',$value['files']);
                }
            }
        }
        $data  =array('code'=>1,'msg'=>'工作列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }

    /**
     *  工资单
     * @ApiMethod (POST)
     */
    public function gongzidan()
    {
        $page =    $this->request->get('page');
        $pageSize = $this->request->get('pageSize');
        $whereU =['uid'=>$this->auth->id];

        $total = Db::name('yonghugongzidan')->where($whereU)->count();
        $pagesNum  = ceil($total/$pageSize);
        $list  = Db::name('yonghugongzidan')->where($whereU)->limit(($page-1)*$pageSize, $pageSize)->order('id desc')->select();
        if(!empty($list)){
            foreach ($list as $Item =>$value){
                $list[$Item]['fafangriqi'] = date('Y-m-d H:i:s',$value['fafangriqi']);
                $list[$Item]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
            }
        }
        $data  =array('code'=>1,'msg'=>'工资单列表','data'=>['total' => $total,'currentPage' => $page,'pagesNum' => $pagesNum,'rows' => $list]);
        return json($data);
    }
    /**
     * 用户余额
     * @ApiMethod (POST)
     */
    public function userMoney()
    {
        $userMoney  =    Db::name('user')->where('id',$this->auth->id)->find();
        echo Db::name('user')->getLastSql();
        $this->success('返回列表', $userMoney);
    }
    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }

}
